package org.cqust.backend.service;

import org.cqust.backend.dto.request.data.SaveUserSettingRequestDTO;
import org.cqust.backend.dto.request.data.SaveUserTopologyRequestDTO;
import org.cqust.backend.dto.response.data.ImageSummaryDTO;
import org.cqust.backend.dto.response.data.UserSettingDTO;
import org.cqust.backend.dto.response.data.UserTopologyDTO;
import org.cqust.backend.entity.ImageData;
import org.cqust.backend.entity.UserSettingJson;
import org.cqust.backend.entity.UserTopologyXml;
import org.cqust.backend.exception.BusinessException;
import org.cqust.backend.repository.ImageDataRepository;
import org.cqust.backend.repository.SettingJsonDataRepository;
import org.cqust.backend.repository.TopologyXmlDataRepository;
import org.cqust.backend.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class DataService {

    private final SettingJsonDataRepository settingJsonDataRepository;
    private final TopologyXmlDataRepository topologyXmlDataRepository;
    private final ImageDataRepository imageDataRepository;
    private final UserRepository userRepository;

    public DataService(SettingJsonDataRepository settingJsonDataRepository, TopologyXmlDataRepository topologyXmlDataRepository, ImageDataRepository imageDataRepository, UserRepository userRepository) {

        this.settingJsonDataRepository = settingJsonDataRepository;
        this.topologyXmlDataRepository = topologyXmlDataRepository;
        this.imageDataRepository = imageDataRepository;
        this.userRepository = userRepository;
    }

    public byte[] getImageBytes(long id) {
        return imageDataRepository.findById(id)
                .orElseThrow(() -> new BusinessException("未找到ID为 " + id + " 的Image"))
                .getImageBytes();
    }

    public UserSettingDTO getSettingJson(long userId) {
        UserSettingJson userSettingJson = settingJsonDataRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("未找到User ID为 " + userId + " 的SettingJson"));

        UserSettingDTO userSettingDTO = new UserSettingDTO();
        userSettingDTO.setSettingJson(userSettingJson.getJson());
        return userSettingDTO;
    }
    @Transactional
    public void saveSettingJson(SaveUserSettingRequestDTO requestDTO) {
        if(!userRepository.existsById(requestDTO.getUserId()))
            throw new BusinessException("User ID为 " + requestDTO.getUserId() + " 的User不存在");
        settingJsonDataRepository.deleteById(requestDTO.getUserId());
        UserSettingJson userSettingJson = new UserSettingJson();
        userSettingJson.setUserId(requestDTO.getUserId());
        userSettingJson.setJson(requestDTO.getSettingJson());
        settingJsonDataRepository.save(userSettingJson);
    }
    public UserTopologyDTO getTopologyXml(long userId) {
        UserTopologyXml userTopologyXml = topologyXmlDataRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("未找到User ID为 " + userId + " 的TopologyXml"));

        UserTopologyDTO userTopologyDTO = new UserTopologyDTO();
        userTopologyDTO.setTopologyXml(userTopologyXml.getXml());
        return userTopologyDTO;
    }
    @Transactional
    public void saveTopologyXml(SaveUserTopologyRequestDTO requestDTO) {
        if(!userRepository.existsById(requestDTO.getUserId()))
            throw new BusinessException("User ID为 " + requestDTO.getUserId() + " 的User不存在");
        topologyXmlDataRepository.deleteById(requestDTO.getUserId());
        UserTopologyXml userTopologyXml = new UserTopologyXml();
        userTopologyXml.setUserId(requestDTO.getUserId());
        userTopologyXml.setXml(requestDTO.getTopologyXml());
        topologyXmlDataRepository.save(userTopologyXml);
    }

    public String getMissionXml(long missionId) {
        return null;
    }

    public List<ImageSummaryDTO> getAllImage(){
        return imageDataRepository.findAllDescriptionAndId();
    }
    @Transactional
    public Long saveImage(MultipartFile file) {
        try {
            // 获取文件字节数据
            byte[] imageBytes = file.getBytes();

            // 创建实体对象并保存到数据库
            ImageData imageData = new ImageData();
            imageData.setImageBytes(imageBytes);

            ImageData saved = imageDataRepository.save(imageData);

            // 返回生成的 ID（使用数据库自增）
            return saved.getId();
        } catch (IOException e) {
            throw new RuntimeException("图片读取失败: " + e.getMessage(), e);
        }
    }
}